package com.jinzhu.controller;

import com.jinzhu.bo.UsersBO;
import com.jinzhu.pojo.Users;
import com.jinzhu.service.UserService;
import com.jinzhu.utils.CookieUtils;
import com.jinzhu.utils.IMOOCJSONResult;
import com.jinzhu.utils.JsonUtils;
import com.jinzhu.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;


/**
 * @author jinzhu
 * 用户管理
 */
@RestController
@RequestMapping("/passport")
//构造器注解
@AllArgsConstructor
@Api(value = "users", tags = "用户管理")
@Slf4j
public class UsersController {
    //构造器注入
    private final UserService userService;

    /**
     * @author jinzhu
     * @date 2021-03-31
     * @param username 用户名
     * @return IMOOCJSONResult
     *
     * 注册查询用户是否存在                                                                                                                  是否存在
     */
    @ApiOperation(value = "用户名是否存在", notes = "用户名是否存在", httpMethod = "GET")
    @GetMapping("/usernameIsExist")
    public IMOOCJSONResult queryUserNameIsExist(@RequestParam(value = "username") String username) {
        //判断用户名是否为null
        if (StringUtils.isEmpty(username)) {
            return IMOOCJSONResult.errorMsg("用户名不能为空");
        }
        //查找用户名是否存在
        Boolean aBoolean = userService.queryUserNameIsExist(username);
        return aBoolean == true ? IMOOCJSONResult.ok() : IMOOCJSONResult.errorMsg("用户名存在");
    }


    /**
     * @param usersBO
     * @date 2021-03-31
     * @return IMOOCJSONResult
     * @author jinzhu
     * 注册添加用户
     */
    @ApiOperation(value = "用户注册", notes = "用户注册", httpMethod = "POST")
    @PostMapping("/regist")
    public IMOOCJSONResult regist(@RequestBody UsersBO usersBO) {

        //1 判断密码是否等于null
        if (StringUtil.isEmpty(usersBO.getUsername())) {
            return IMOOCJSONResult.errorMsg("用户名不能为空");
        }

        //2.判断密码长度是否等于6
        if (usersBO.getPassword().length() != 6) {
            return IMOOCJSONResult.errorMsg("密码长度要等于6");
        }

        //3.判断二次密码是否一致
        if (!Objects.equals(usersBO.getPassword(), usersBO.getConfirmPassword())) {
            return IMOOCJSONResult.errorMsg("二次密码不一致");
        }
        //TODO  后期需要维护修改
        //4.注册用户
        Users users = userService.insertUser(usersBO);
        return IMOOCJSONResult.ok(users);
    }
    /**
     * @param usersBO
     * @date 2021-04-10
     * @return IMOOCJSONResult
     * @author jinzhu
     * 登录
     */
    @ApiOperation(value = "用户登录", notes = "用户登录", httpMethod = "POST")
    @PostMapping("/login")
    public IMOOCJSONResult login(@RequestBody UsersBO userBO,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {

        String username = userBO.getUsername();
        String password = userBO.getPassword();

        // 0. 判断用户名和密码必须不为空
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password)) {
            return IMOOCJSONResult.errorMsg("用户名或密码不能为空");
        }

        // 1. 实现登录
        Users userResult = userService.queryUserForLogin(username,
                MD5Utils.getMD5Str(password));

        if (userResult == null) {
            return IMOOCJSONResult.errorMsg("用户名或密码不正确");
        }
        //如果用户登录 一些没必要的返回null
        userResult = setNullProperty(userResult);
        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(userResult), true);

        // TODO 生成用户token，存入redis会话
        // TODO 同步购物车数据

        return IMOOCJSONResult.ok(userResult);
    }
    /**
     * @param usersBO
     * @date 2021-04-10
     * @return IMOOCJSONResult
     * @author jinzhu
     * 注销
     */
    @ApiOperation(value = "用户退出登录", notes = "用户退出登录", httpMethod = "POST")
    @PostMapping("/logout")
    public IMOOCJSONResult logout(@RequestParam String userId,
                                  HttpServletRequest request,
                                  HttpServletResponse response) {

        //FIXME  后期错误不需要的 清除用户的相关信息的cookie
        CookieUtils.deleteCookie(request, response, "user");
        // TODO 需要做的 用户退出登录，需要清空购物车
        // TODO 需要做的 分布式会话中需要清除用户数据
        return IMOOCJSONResult.ok();
    }

    /**
     *如果用户登录 一些没必要的返回null
     * @param userResult
     * @return
     */
    private Users setNullProperty(Users userResult) {
        userResult.setPassword(null);
        userResult.setMobile(null);
        userResult.setEmail(null);
        userResult.setCreatedTime(null);
        userResult.setUpdatedTime(null);
        userResult.setBirthday(null);
        return userResult;
    }
}
